package com.zero.order.service;

import com.zero.account.api.AccountServiceApi;
import com.zero.order.entity.OrderEntity;
import com.zero.order.mapper.OrderMapper;
import com.zero.storage.api.StorageServiceApi;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

/**
 * @author zero
 * @ClassName OrderService
 * @Description
 * @Date 2025/5/15 13:37
 */
@Slf4j
@Service
public class OrderService {
    private OrderMapper orderMapper;
    private AccountServiceApi accountService;
    private StorageServiceApi storageService;
    public OrderService(OrderMapper orderMapper, AccountServiceApi accountService, StorageServiceApi storageService) {
        this.orderMapper = orderMapper;
        this.accountService = accountService;
        this.storageService = storageService;
    }
    /**
     * 下单
     */
    @GlobalTransactional
    public Long create(OrderEntity order) {
        try {
            // 创建订单
            orderMapper.insert(order);
            accountService.deduct(order.getUserId(), order.getMoney());
            storageService.deduct(order.getCommodityCode(), order.getCount());
        }catch (FeignException e){
            log.error("下单失败，原因:{}", e.contentUTF8(), e);
            throw new RuntimeException(e.contentUTF8(), e);
        }
        return order.getId();

    }
    /**
     * 撤单
     */
    @GlobalTransactional
    public void cancel(Long orderId) {
        OrderEntity order = orderMapper.selectById(orderId);
        accountService.refund(order.getUserId(), order.getMoney());
        storageService.refund(order.getCommodityCode(), order.getCount());
        orderMapper.deleteById(orderId);
    }
    /**
     * 查询订单
     */
    public OrderEntity query(Long orderId) {
        return orderMapper.selectById(orderId);
    }
    /**
     * 测试负载均衡
     */
    public String loadBalance() {
        return accountService.loadBalance();
    }


}
